<template>
  <div>
    <vxe-toolbar
      id="toolbarId_bi7"
      :custom="{ storage: true }"
      export
      :refresh="{ query: findList }"
    >
      <template v-slot:buttons>
        <el-button @click="funcFilter">查询</el-button>
        <el-button v-if="!parentData.isDetail" @click="funcAdd">新增</el-button>
      </template>
    </vxe-toolbar>
    <vxe-table
      ref="xTable"
      border
      resizable
      stripe
      highlight-current-row
      highlight-hover-row
      row-id="id"
      height="700"
      :data="tableData"
      :loading="loading"
      :sort-config="{ remote: true }"
      export-config
      show-overflow
      align="center"
      @sort-change="sortList"  
    >
      <vxe-table-column type="checkbox" width="60"  />
      <vxe-table-column>
        <vxe-table-column
          field="userCode"
          :formatter="formatterUserCode"
          title="上游客户"
          min-width="130"
          sortable
        />
        <template v-slot:header>
          <el-select v-model="listQuery.userCode" placeholder="请选择" clearable>
            <el-option
              v-for="item in parentData.upstreamCustomerList"
              :key="item.partyCode"
              :label="item.userName"
              :value="item.partyCode"
            />
          </el-select>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column
          field="coalBigType"
          :formatter="formatterCoalBigType"
          title="货物类型（大）"
          min-width="150"
          sortable
        />
        <template v-slot:header>
          <el-select v-model="listQuery.coalBigType" placeholder="货物类型（大）" clearable>
            <el-option
              v-for="item in parentData.goodsTypeList"
              :key="item.code"
              :label="item.label"
              :value="item.code"
              clearable
            />
          </el-select>
        </template>
      </vxe-table-column>
      <vxe-table-column v-if="!isCtms">
        <vxe-table-column
          field="coalType"
          :formatter="formatterCoalType"
          title="货物类型（小）"
          min-width="150"
          sortable
        />
        <template v-slot:header>
          <el-select v-model="listQuery.coalType" placeholder="货物类型（小）" clearable>
            <el-option
              v-for="item in goodsTypeList2"
              :key="item.code"
              :label="item.label"
              :value="item.code"
              clearable
            />
          </el-select>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column
          field="classificationCode"
          :formatter="formatterClassificationCode"
          title="车型"
          min-width="130"
          sortable
        />
        <template v-slot:header>
          <el-select v-model="listQuery.classificationCode" placeholder="车型" clearable>
            <el-option
              v-for="item in parentData.vehicleDictList"
              :key="item.code"
              :label="item.name"
              :value="item.code"
              clearable
            />
          </el-select>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="originName" title="起始地" min-width="130" sortable />
        <template v-slot:header>
          <el-cascader
            v-model="shipperSubdivisionArray"
            :options="parentData.areaOptions"
            :props="{ value: 'countyCode', label: 'countyName' }"
            clearable
            @change="changeShipperSubdivisionArray"
          />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="destName" title="目的地" min-width="130" sortable />
        <template v-slot:header>
          <el-cascader
            v-model="consigneeSubdivisionArray"
            :options="parentData.areaOptions"
            :props="{ value: 'countyCode', label: 'countyName' }"
            clearable
            @change="changeConsigneeSubdivisionArray"
          />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="price" title="应收单价" min-width="200" sortable />
        <template v-slot:header>
          <el-row>
            <el-col :span="11">
              <el-input type="number" v-model="listQuery.priceStart" placeholder="下限" clearable />
            </el-col>
            <el-col :span="11" :offset="2">
              <el-input type="number" v-model="listQuery.priceEnd" placeholder="上限" clearable />
            </el-col>
          </el-row>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="allFee" title="应收总价" min-width="200" sortable />
        <template v-slot:header>
          <el-row>
            <el-col :span="11">
              <el-input type="number" v-model="listQuery.allFeeStart" placeholder="下限" clearable />
            </el-col>
            <el-col :span="11" :offset="2">
              <el-input type="number" v-model="listQuery.allFeeEnd" placeholder="上限" clearable />
            </el-col>
          </el-row>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column
          field="gmtCreated"
          min-width="420"
          title="注册时间"
          sortable
        />
        <template v-slot:header>
          <el-date-picker
            v-model="gmtCreatedRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="changeDate"
          />
        </template>
      </vxe-table-column>
      <vxe-table-column v-if="!parentData.isDetail"  field="action" title="操作" min-width="130" fixed="right">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" content="编辑" placement="top">
            <vxe-button type="text" @click="funcEdit(scope.row.code)">
              <i class="el-icon-edit" />
            </vxe-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="删除" placement="top">
            <vxe-button type="text" @click="funcDelete(scope.row.code)">
              <i class="el-icon-delete" />
            </vxe-button>
          </el-tooltip>
        </template>
      </vxe-table-column>
    </vxe-table>
    <vxe-pager
      :loading="loading"
      :current-page.sync="listQuery.pageNum"
      :page-size.sync="listQuery.pageSize"
      :total="listQuery.total"
      :page-sizes="Pagingconf"
      :layouts="['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total']"
      @page-change="handlePageChange"
    />
    <vxe-modal v-model="modelAddFlag" title="新增" width="800" height="500" resize>
      <compAdd
        :parentData="parentData"
        @fatherAddMethod="fatherAdd"
        @fatherCancelMethod="fatherCancel"
      />
    </vxe-modal>
    <vxe-modal v-model="modelEditFlag" title="编辑" width="800" height="500" resize>
      <compEdit
        ref="editRef"
        :parentData="parentData"
        @fatherEditMethod="fatherEdit"
        @fatherCancelMethod="fatherCancel"
      />
    </vxe-modal>
  </div>
</template>
<script>
import compAdd from "./components/upstreamCustomerAdd.vue";
import compEdit from "./components/upstreamCustomerEdit.vue";
import { getUpstreamCustomerList, delUpstreamCustomer } from "@/api/shipment";
import { getRole } from '@/utils/getRole'
export default {
  name: "UpstreamCustomerList",
  components: {
    compAdd,
    compEdit
  },
  props: {
    parentData: {
      type: Object,
      default() {
        return {
          isDetail: false,
          areaOptions: [],
          goodsTypeList: [],
          typeOptions: [],
          vehicleDictList: [],
          bankOptions: [],
          receiverUserCodeOptions: [],
          upstreamCustomerList: []
        };
      }
    }
  },
  data() {
    return {
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            }
          }
        ]
      },
      loading: false,
      tableData: [],
      modelAddFlag: false,
      modelEditFlag: false,
      shipperSubdivisionArray: [],
      consigneeSubdivisionArray: [],
      gmtCreatedRange: "",
      listQuery: {
        companyCode: "",
        userCode: "",
        coalBigType: "",
        coalType: "",
        shipperSubdivisionCode: "",
        consigneeSubdivisionCode: "",
        gmtCreatedStart: "",
        gmtCreatedEnd: "",
        staffType: "5",
        pageNum: 1,
        pageSize: 20,
        sortField: "",
        sortType: "",
        total: 0,
        isCtms:true,

      },
      Pagingconf: []
    };
  },
  computed: {
    goodsTypeList2() {
      var list = [];
      this.parentData.goodsTypeList.forEach(item => {
        if (item.code === this.listQuery.coalBigType && item.children) {
          list.push.apply(list, item.children);
        }
      });
      return list;
    }
  },
  created() {
    this.listQuery.companyCode = this.$route.query.code
      ? this.$route.query.code
      : "";
     this.findList();
     this.isCtms = getRole()
  },
  methods: {
    findList() {
      this.loading = true;
      return new Promise(resolve => {
        getUpstreamCustomerList(this.listQuery).then(response => {
          this.tableData = response.data.records;
          this.listQuery.total = response.data.total;
          this.Pagingconf = [20, 30, 50, 100, response.data.total||1];
          this.loading = false;
          resolve();
        });
      });
    },
    changeShipperSubdivisionArray(value) {
      this.listQuery.shipperSubdivisionCode = value[2];
    },
    changeConsigneeSubdivisionArray(value) {
      this.listQuery.consigneeSubdivisionCode = value[2];
    },
    formatterUserCode({ cellValue }) {
      const item = this.parentData.upstreamCustomerList.find(
        item => item.partyCode === cellValue
      );
      return item ? item.userName : "";
    },
    // 格式化 车型
    formatterClassificationCode({ cellValue }) {
      const item = this.parentData.vehicleDictList.find(
        item => item.code === cellValue
      );
      return item ? item.name : "";
    },
    // 格式化 货物类型（大）
    formatterCoalBigType({ cellValue }) {
      const item = this.parentData.goodsTypeList.find(
        item => item.code === cellValue
      );
      return item ? item.label : "";
    },
    // 格式化 货物类型（小）
    formatterCoalType({ cellValue, row }) {
      var item = this.parentData.goodsTypeList.find(
        item => item.code === row.coalBigType
      );
      if (item && item.children) {
        item.children = item.children ? item.children : [];
      } else {
        return "";
      }
      var sub_item = item.children.find(item => item.code === cellValue);
      return sub_item ? sub_item.label : "";
    },
    // 查询
    funcFilter() {
      this.listQuery.pageNum = 1;
      this.findList();
    },
    // 排序
    sortList({ column, property, order }) {
      var str;
      switch (property) {
        case "consignorAddress":
          str = "consignorCountyCode";
          break;
        case "consigneeAddress":
          str = "consigneeCountyCode";
          break;
        default:
          str = property;
          break;
      }
      if (order) {
        this.listQuery.sortField = str;
        this.listQuery.sortType = order;
      } else {
        this.listQuery.sortField = "";
      }
      this.findList();
    },
    changeDate(value) {
      if (value) {
        this.listQuery.gmtCreatedStart = value[0] + " 00:00:00";
        this.listQuery.gmtCreatedEnd = value[1] + " 23:59:59";
      } else {
        this.listQuery.gmtCreatedStart = "";
        this.listQuery.gmtCreatedEnd = "";
      }
    },
    // 添加方法
    funcAdd() {
      this.modelAddFlag = true;
    },
    // 修改方法
    funcEdit(code) {
      this.$refs.editRef.getInfo(code);
      this.modelEditFlag = true;
    },
    // 删除方法
    funcDelete(codes) {
      this.$confirm("确认删除吗？")
        .then(_ => {
          delUpstreamCustomer({ codes }).then(response => {
            this.$message({ message: response.msg, type: "success" });
            this.findList();
          });
        })
        .catch(_ => {});
    },
    // 增加组件的父方法
    fatherAdd() {
      this.modelAddFlag = false;
      this.findList();
    },
    // 编辑组件的父方法
    fatherEdit() {
      this.modelEditFlag = false;
      this.findList();
    },
    // 公共取消
    fatherCancel(modelFlag) {
      switch (modelFlag) {
        case "add":
          this.modelAddFlag = false;
          break;
        case "edit":
          this.modelEditFlag = false;
          break;
      }
    },
    // 分页handle
    handlePageChange({ currentPage, pageSize }) {
      this.listQuery.pageNum = currentPage;
      this.listQuery.pageSize = pageSize;
      this.findList();
    }
  }
};
</script>

<style>
</style>
